//
//  WmcCloudPhotoCell.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/28.
//

import UIKit
import Kingfisher

class WmcCloudPhotoCell: WmcBaseCollectionCell {
    override func makeUI() {
        titleLabel.textAlignment = .center
        titleLabel.backgroundColor = .clear
        titleLabel.textColor = .white
        titleLabel.font = 17.wmc_font

        imageView.contentMode = .scaleAspectFill
        imageView.backgroundColor = .wmc_grayH11_9D9DB3
        imageView.clipsToBounds = true

        contentView.addSubview(imageView)
        contentView.addSubview(titleView)
        contentView.addSubview(videoIconImageView)
        titleView.addSubview(titleLabel)
        
        imageView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }

        titleView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(35)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.bottom.left.right.equalToSuperview()
        }
        
        videoIconImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(28)
        }
    }
    
    lazy var titleView: UIView = {
        let view: UIView = UIView()
        view.layer.addSublayer(self.createGradientLayer())
        return view
    }()
    
    
    func createGradientLayer() -> CAGradientLayer {
        let gradientLayer = CAGradientLayer()

        gradientLayer.colors = [
            "#000000".yp.cgColor(0.6),
            UIColor.clear.cgColor,
        ]

        gradientLayer.locations = [0, 1]
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
        let width = (UIScreen.main.bounds.width - 38) / 3.0
        gradientLayer.frame = CGRect(x: 0, y: 0, width: width, height: 35)
        return gradientLayer
    }
    
    private lazy var videoIconImageView: UIImageView = {
        let view = UIImageView(image: "player_play_center".wmc_image)
        view.isHidden = true
        return view
    }()

    func bindModel(_ model: WmcMediaPhotoModel) {
        if model.loadStatus == .loadFailure {
            imageView.image = "photo_load_failure".wmc_image
            return
        }
        
        var params = ""
        
        if model.resourceType == 0 {
            params = "x-oss-process=image/resize,h_200,m_lfit"
            videoIconImageView.isHidden = true
        } else if model.resourceType == 1 {
            params = "x-oss-process=video/snapshot,t_7000,ar_auto,f_jpg,m_fast"
            videoIconImageView.isHidden = false
        }
        
        var url = "\(model.url)"
        var symbol = "?"
        if url.contains(symbol) {
            symbol = "&"
        }
        url.append(contentsOf: "\(symbol)\(params)")
        
        if let imgUrl = URL(string: url) {
            let urlParts = model.url.components(separatedBy: "?")
            var key = model.url
            if urlParts.count == 2 {
                key = urlParts[0]
            }
            key.append("/thumb")
            imageView.kf.setImage(with: .network(Kingfisher.ImageResource(downloadURL: imgUrl, cacheKey: key)), placeholder: "image_placeholder".wmc_image, completionHandler:  { [weak self] r in
                guard let weakSelf = self else { return }
                switch r {
                case .success(_):
                    model.loadStatus = .loadsuccess
                case .failure(_):
                    model.loadStatus = .loadFailure
                    weakSelf.imageView.image = "photo_load_failure".wmc_image
                }
            })
        }
        
        titleLabel.text = model.takeTimeStr
    }
}

extension WmcCloudPhotoCell {
    
    /// 模型变了，为了复用之前UI，不该UI，扩展一个新模型的构造方法
    
    func configure(model: WmcMediaClassifyAlbumMemberModel) -> Void {
        if model.loadStatus == .loadFailure {
            imageView.image = "photo_load_failure".wmc_image
            return
        }
        
        var params = ""
        
        if model.resourceType == 0 {
            params = "x-oss-process=image/resize,h_200,m_lfit"
            videoIconImageView.isHidden = true
        } else if model.resourceType == 1 {
            params = "x-oss-process=video/snapshot,t_7000,ar_auto,f_jpg,m_fast"
            videoIconImageView.isHidden = false
        }
        
        var url = "\(model.url)"
        var symbol = "?"
        if url.contains(symbol) {
            symbol = "&"
        }
        url.append(contentsOf: "\(symbol)\(params)")
        
        if let imgUrl = URL(string: url) {
            let urlParts = model.url.components(separatedBy: "?")
            var key = model.url
            if urlParts.count == 2 {
                key = urlParts[0]
            }
            key.append("/thumb")
            imageView.kf.setImage(with: .network(Kingfisher.ImageResource(downloadURL: imgUrl, cacheKey: key)), placeholder: "image_placeholder".wmc_image, completionHandler:  { [weak self] r in
                guard let weakSelf = self else { return }
                switch r {
                case .success(_):
                    model.loadStatus = .loadsuccess
                case .failure(_):
                    model.loadStatus = .loadFailure
                    weakSelf.imageView.image = "photo_load_failure".wmc_image
                }
            })
        }
        
        titleLabel.text = model.takeTimeStr
    }
}
